package com.ece.devirtualizus.Activities;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.ece.devirtualizus.R;
import com.ece.devirtualizus.Application.StartApplication;
import com.ece.devirtualizus.Dao.ReleveDao;
import com.ece.devirtualizus.Detectors.StepDetector;
import com.ece.devirtualizus.ModelDto.Modules;
import com.ece.devirtualizus.ModelDto.ResultatSessionDto;
import com.ece.devirtualizus.ModelDto.User;

import com.parse.ParseUser;

import org.achartengine.ChartFactory;
import org.achartengine.chart.BarChart.Type;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;

import android.app.Activity;
import android.graphics.Color;
import android.graphics.Paint.Align;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;

public class ModuleGraphsActivity extends Activity{
	
	TextView step_number;
	StepDetector step;
	SensorManager sensorManager;
	User user;
	Modules typeModule;

	private View mChart;
	private ReleveDao relevedao;

	List<ResultatSessionDto> sessionHisto;
	//List<Date> allDateForGraph;
	List<Integer> allReleveForGraph;
//	List<Integer> nbOfValues;
	int maxForScale;
	Calendar aujourdhui;
	Date dateEndSearch;
	Date dateBeginSearch;
	
	List<Calendar> weekPrint ;
	static int daysBefore = 7;

	
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    
	    // remove title . FULL SCREEN
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
	    setContentView(R.layout.module_graphs);

	   // StartApplication app = (StartApplication)getApplication();
	   // user = app.getUser();
	    
	    
	    //user = getIntent().getExtras().getParcelable("user");
	    typeModule = (Modules) getIntent().getExtras().getSerializable("module");

	    weekPrint = new ArrayList<Calendar>();
	    
	    //step_number = (TextView) findViewById(R.id.textView1);
	    //step_number.setText("Nombre de pas: "+ user.getSteps());
	/*******DEBUT PATIE POUR LES GRAPHES *******/
    	Log.e("clickListener","Je suis ici 1");
   	 
    	openGraphByModule(typeModule);


	/*******FIN PARTIE POUR LES GRAPHES *******/

	}
	
	@Override
	protected void onResume() 
	{	   
		super.onResume();
		Log.d("************MODULE PAS ACTIVITY************", "RESUME");
	}
	
	@Override	  	
	protected void onPause() 
	{	 
		Log.d("************MODULE PAS ACTIVITY************", "PAUSE");
	    super.onPause();
	}
	
	@Override	  	
	protected void onDestroy() 
	{	 
		Log.d("************MODULE PAS ACTIVITY************", "DESTROY");
	    super.onDestroy();
	}
	
	public void openGraphByModule(Modules type_module)
	{
		switch (type_module) {
		case PUSH_UP:
			Log.d("-------------GraphType", "PUSHUP");
			
			aujourdhui = Calendar.getInstance();
			Log.d("aujourdh'ui",aujourdhui.toString() );
			dateEndSearch = aujourdhui.getTime();
			aujourdhui.add(Calendar.DATE, -daysBefore);
			dateBeginSearch = aujourdhui.getTime();
			
			fillDataForChartByDate(type_module, dateBeginSearch, dateEndSearch);
			openChart(type_module, Color.rgb(244, 120, 4), Color.rgb(255, 255, 255), Color.rgb(255, 255, 255));
			break;
			
		case FOOTING_EXT:
			Log.d("-------------GraphType", "FOOTING EXT");
			aujourdhui = Calendar.getInstance();
			dateEndSearch = aujourdhui.getTime();
			aujourdhui.add(Calendar.DATE, -2);
			dateBeginSearch = aujourdhui.getTime();
			
			fillDataForChartByDate(type_module, dateBeginSearch, dateEndSearch);
			openChart(type_module, Color.rgb(118, 193, 42), Color.rgb(255, 255, 255), Color.rgb(255, 255, 255));
			break;
			
		case FOOTING_INT:
			Log.d("-------------GraphType", "FOOTING INT");
			aujourdhui = Calendar.getInstance();
			dateEndSearch = aujourdhui.getTime();
			aujourdhui.add(Calendar.DATE, -2);
			dateBeginSearch = aujourdhui.getTime();
			
			fillDataForChartByDate(type_module, dateBeginSearch, dateEndSearch);
			openChart(type_module, Color.rgb(91, 137, 183), Color.rgb(255, 255, 255), Color.rgb(255, 255, 255));
			break;
			
		case ABS:
			Log.d("-------------GraphType", "ABS");
			aujourdhui = Calendar.getInstance();
			dateEndSearch = aujourdhui.getTime();
			aujourdhui.add(Calendar.DATE, -daysBefore);
			dateBeginSearch = aujourdhui.getTime();
			
			fillDataForChartByDate(type_module, dateBeginSearch, dateEndSearch);
			openChart(type_module, Color.rgb(242, 33, 33), Color.rgb(255, 255, 255), Color.rgb(255, 255, 255));
			break;
			
		case STEP_COUNTER:
			Log.d("-------------GraphType", "STEP");
			aujourdhui = Calendar.getInstance();
			dateEndSearch = aujourdhui.getTime();
			aujourdhui.add(Calendar.DATE, -2);
			dateBeginSearch = aujourdhui.getTime();
			
			fillDataForChartByDate(type_module, dateBeginSearch, dateEndSearch);
			openChart(type_module, Color.rgb(234, 234, 18), Color.rgb(255, 255, 255), Color.rgb(255, 255, 255));
			break;
			
		default:
			break;		
		}
		
	}
	
	private void openChart(Modules type_module, int colorBar, int colorBackground, int colorMargin){
		Log.e("openChart","Je suis ici 1");
		
		List<String>dateRelev = new ArrayList<String>();
		//affichage date
		for(int i=0;i<daysBefore;i++){
			if ( ((weekPrint.get(i).getTime().getMonth()+1) > 0) && ((weekPrint.get(i).getTime().getMonth()+1) < 10) )
			{
				dateRelev.add(weekPrint.get(i).getTime().getDate() + "/" + "0" + (weekPrint.get(i).getTime().getMonth()+1) + "\n");
			}
		 }
		
		 // Creating an XYSeries for Income
		 XYSeries allReleveForGraphSeries = new XYSeries(type_module.toString());
		 // Creating an XYSeries for Expense
		 // Adding data to Income and Expense Series
		 for(int i=0;i<daysBefore;i++){
			 allReleveForGraphSeries.add(i,allReleveForGraph.get(i));
		 }

		 // Creating a dataset to hold each series
		 XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
		 // Adding Income Series to the dataset
		 dataset.addSeries(allReleveForGraphSeries);
		 // Adding Expense Series to dataset

		 // Creating XYSeriesRenderer to customize incomeSeries
		 XYSeriesRenderer allReleveForGraphRenderer = new XYSeriesRenderer();
		 allReleveForGraphRenderer.setColor(colorBar); //color of the graph 
		 allReleveForGraphRenderer.setFillPoints(true);
		 allReleveForGraphRenderer.setLineWidth(0.1f);
		 allReleveForGraphRenderer.setDisplayChartValues(true);
		 allReleveForGraphRenderer.setDisplayChartValuesDistance(1); //setting chart value distance 


		 // Creating a XYMultipleSeriesRenderer to customize the whole chart
		 XYMultipleSeriesRenderer multiRenderer = new XYMultipleSeriesRenderer();
		 multiRenderer.setOrientation(XYMultipleSeriesRenderer.Orientation.HORIZONTAL);
		 multiRenderer.setXLabels(0);
		 multiRenderer.setChartTitle(type_module.toString()+" / Time");
		 //multiRenderer.setXTitle("Time");
		 multiRenderer.setXTitle("");
		 multiRenderer.setYTitle(type_module.toString());

		 multiRenderer.setXLabelsColor(Color.rgb(0, 0, 0)); 
		 multiRenderer.setYLabelsColor(0, Color.rgb(0, 0, 0));
		 multiRenderer.setAxesColor(Color.rgb(0, 0, 0));
		 
		 /***
		 * Customizing graphs
		 */
		 //setting text size of the title
		 multiRenderer.setChartTitleTextSize(28);
		 //setting text size of the axis title
		 multiRenderer.setAxisTitleTextSize(24);
		 //setting text size of the graph label
		 multiRenderer.setLabelsTextSize(24);
		 //setting zoom buttons visibility
		 multiRenderer.setZoomButtonsVisible(false);
		 //setting pan enablity which uses graph to move on both axis
		 multiRenderer.setPanEnabled(false, false);
		 //setting click false on graph
		 multiRenderer.setClickEnabled(false);
		 //setting zoom to false on both axis
		 multiRenderer.setZoomEnabled(false, false);
		 //setting lines to display on y axis
		 multiRenderer.setShowGridY(true);
		 //setting lines to display on x axis
		 multiRenderer.setShowGridX(true);
		 //setting legend to fit the screen size
		 multiRenderer.setFitLegend(true);
		 //setting displaying line on grid
		 multiRenderer.setShowGrid(false);
		 //setting zoom to false
		 multiRenderer.setZoomEnabled(true);
		 //setting external zoom functions to false
		 multiRenderer.setExternalZoomEnabled(false);
		 //setting displaying lines on graph to be formatted(like using graphics)
		 multiRenderer.setAntialiasing(true);
		 //setting to in scroll to false
		 multiRenderer.setInScroll(false);
		 //setting to set legend height of the graph
		 multiRenderer.setLegendHeight(30);
		 //setting x axis label align
		 multiRenderer.setXLabelsAlign(Align.CENTER);
		 //setting y axis label to align
		 multiRenderer.setYLabelsAlign(Align.LEFT);
		 //setting text style
		 multiRenderer.setTextTypeface("sans_serif", Typeface.NORMAL);
		 //setting no of values to display in y axis
		 multiRenderer.setYLabels(10);
		 // setting y axis max value, Since i'm using static values inside the graph so i'm setting y max value to 4000.
		 // if you use dynamic values then get the max y value and set here
		 if (maxForScale<6)
			 multiRenderer.setYAxisMax(6);
		 else 
			 multiRenderer.setYAxisMax(maxForScale + 10);
		 multiRenderer.setYAxisMin(0);
		 //setting used to move the graph on xaxiz to .5 to the right
		 multiRenderer.setXAxisMin(-1);
		//setting max values to be display in x axis
		 multiRenderer.setXAxisMax(7);
		 //setting bar size or space between two bars
		 multiRenderer.setBarSpacing(0.5);
		 //Setting background color of the graph to transparent
		 multiRenderer.setBackgroundColor(colorBackground);
		 //Setting margin color of the graph to transparent
		 //multiRenderer.setMarginsColor(getResources().getColor(R.color.transparent_background));
		 multiRenderer.setMarginsColor(colorMargin);
		 multiRenderer.setApplyBackgroundColor(true);
		 
		 

		 //setting the margin size for the graph in the order top, left, bottom, right
		 multiRenderer.setMargins(new int[]{100, 30, 30, 30});

		 for(int i=0; i< daysBefore;i++){
			 multiRenderer.addXTextLabel(i, dateRelev.get(i));
		 }

		 // Adding incomeRenderer and expenseRenderer to multipleRenderer
		 // Note: The order of adding dataseries to dataset and renderers to multipleRenderer
		 // should be same
		 multiRenderer.addSeriesRenderer(allReleveForGraphRenderer);

		 //this part is used to display graph on the xml
		 LinearLayout chartContainer = (LinearLayout) findViewById(R.id.chart);
		 //remove any views before u paint the chart
		 chartContainer.removeAllViews();
		 //drawing bar chart
		 mChart = ChartFactory.getBarChartView(this, dataset, multiRenderer,Type.DEFAULT);//ICI CONTEXT
		 //adding the view to the linearlayout
		 chartContainer.addView(mChart);
		}

	private void fillDataForChartByDate(Modules module, Date dateBeginSearch, Date dateEndSearch ){
		Log.e("getLSessionHisto","Je suis ici 1");
		sessionHisto = new ArrayList<ResultatSessionDto>();
	//	allDateForGraph = new ArrayList<Date>();
		allReleveForGraph = new ArrayList<Integer>();
	//	nbOfValues = new ArrayList<Integer>();
		relevedao = new ReleveDao();
		maxForScale = 0;
		Calendar dateTemp;
		
		Log.e("getLSessionHisto","Je suis ici 2 : "+ ParseUser.getCurrentUser().getObjectId()+module.toString());
		
		sessionHisto = relevedao.getAllReleveDtoByModuleByDate(ParseUser.getCurrentUser().getObjectId(), module, dateBeginSearch, dateEndSearch);
		
		Log.e("getLSessionHisto","Je suis ici 3");
//		for (ResultatSessionDto r : sessionHisto){
//			//allDateForGraph.add(r.getDateBeginSession());
//			allReleveForGraph.add(r.getCompteur());
//			nbOfValues.add(1);
//			if (maxForScale<r.getCompteur()){
//				maxForScale = r.getCompteur();
//			}
//		}
		
		
		for (int i = 0; i < daysBefore; i++)
		{
			dateTemp = Calendar.getInstance();
			dateTemp.add(Calendar.DATE, -(daysBefore-(i+1)));
			weekPrint.add(dateTemp);
		}
		
		
		int sum;
		Date currentDate;
		
		for (int i = 0; i < daysBefore; i++)
		{
			sum = 0;
			currentDate = weekPrint.get(i).getTime();
			for (int j = 0; j < sessionHisto.size(); j++)
			{
				if (sessionHisto.get(j).getDateBeginSession().getDate() ==  currentDate.getDate())
				{
					sum = sum + sessionHisto.get(j).getCompteur();
				}
			}
			allReleveForGraph.add(sum);
		}
		
		
		for (int i = 0; i < daysBefore; i++)
		{
			if (maxForScale < allReleveForGraph.get(i))
			{
				maxForScale = allReleveForGraph.get(i);
			}
		}

	}

}
